import { goTo } from '@/modules/move'
import TowerController from '@/modules/structures/tower'

export default (pc: PowerCreep) => {
    if (!pc.memory.role) {
        pc.memory.role = 'default'
    }

    if (!pc.room) {
        // 说明 pc 死了
        if (!pc.memory.bornRoom || pc.spawnCooldownTime) return

        const bornRoom = Game.rooms[pc.memory.bornRoom]
        if (!bornRoom || !bornRoom.powerSpawn) return

        pc.spawn(bornRoom.powerSpawn)
        return
    }

    if (!pc.memory.bornRoom) {
        pc.memory.bornRoom = pc.room.name
    }

    if (pc.hits < pc.hitsMax && pc.room.controller?.my) {
        TowerController.allHeal(pc.room.tower || [], pc)
    }

    if (pc.ticksToLive && pc.ticksToLive < 200) {
        pc.memory.renewing = true

        const bornRoom = Game.rooms[pc.memory.bornRoom]
        const powerSpawn = bornRoom.powerSpawn
        if (powerSpawn) {
            if (pc.pos.isNearTo(powerSpawn)) {
                pc.renew(powerSpawn)
            } else {
                goTo(pc, powerSpawn.pos)
            }
        }
        return
    } else if (pc.memory.renewing) {
        delete pc.memory.renewing
    }

    if (pc.powers[PWR_GENERATE_OPS] && !pc.powers[PWR_GENERATE_OPS].cooldown) {
        pc.usePower(PWR_GENERATE_OPS)
    }

    if (!pc.taskType && pc.store.getFreeCapacity() < 50) {
        let target: StructureStorage | StructureTerminal | null = null
        if (pc.room.storage && pc.room.storage.store.getFreeCapacity() > 30000) {
            target = pc.room.storage
        }
        if (pc.room.terminal && pc.room.terminal.store.getFreeCapacity() > 30000) {
            target = pc.room.terminal
        }
        if (target) {
            if (pc.pos.isNearTo(target)) {
                pc.transfer(target, Object.keys(pc.store)[0] as ResourceConstant)
            } else {
                goTo(pc, target.pos)
            }
        }
    }

    // 本 tick 没有调用 goTo 方法则删除缓存
    if (!pc._goTo && pc.memory._go) {
        delete pc.memory._go
    }
}
